﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Cashier_Service;
using Cashier_Interface;
using Cashier.utils;
using Cashier_Utils;

namespace Cashier.payments
{
    public partial class PaymentsControl : UserControl, IDataGridViewData, IPrinter
    {
        private MainForm mainform;
        private static PaymentsControl paymentsControl;
        private PaymentsService paymentsService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        private PaymentsControl(MainForm mainform)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.dataGridView1.ImplementsInstance = this;
            this.paymentsService = new PaymentsService();
            this.comboBoxPaymentsSort1.BindData(mainform);

            this.ControlsSetRights();
            dateTimePicker_startdate.Value = DateTime.Parse(DateTime.Now.Year + "-" + DateTime.Now.Month + "-1");
            this.Dock = DockStyle.Fill;
        }

        /// <summary>
        /// 返回PaymentsControl实例
        /// </summary>
        /// <param name="mainform"></param>
        /// <returns></returns>
        public static PaymentsControl GetPaymentsControl(MainForm mainform)
        {
            if (paymentsControl == null)
                paymentsControl = new PaymentsControl(mainform);
            paymentsControl.RefreshDataGridViewData();
            return paymentsControl;
        }

        #region 功能方法实现

        /// <summary>
        /// 控件设置权限
        /// </summary>
        private void ControlsSetRights()
        {
            Button[] buttons = { button_query, button_create, button_addPaymentsSort };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);
            ContextMenuStrip[] menuStrips = { contextMenuStrip_dgv };
            RightsforControls.RightsforContextMenuStrip(mainform.Admin.RolePurviewtable, menuStrips);
        }

        /// <summary>
        /// 分类控件加载数据
        /// </summary>
        public void ComboBoxBindData()
        {
            this.comboBoxPaymentsSort1.BindData(mainform);
        }

        /// <summary>
        /// 弹出收支输入框
        /// </summary>
        /// <param name="id"></param>
        private void ShowPaymentsAddForm(long id)
        {
            PaymentsAddForm paymentsAddForm = new PaymentsAddForm(mainform, this, id);
            paymentsAddForm.ShowDialog();
        }

        /// <summary>
        /// 删除收支明细
        /// </summary>
        private void DeletePayments()
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                DialogResult result = MessageBox.Show("确定要删除选定数据吗？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                    {
                        sb.Append(row.Cells[0].Value.ToString()).Append(",");
                    }
                    sb.Remove(sb.Length - 1, 1);
                    int count = paymentsService.DeletePayments(sb.ToString());
                    if (count > 0)
                    {
                        MessageBox.Show("删除成功！");
                        this.RefreshDataGridViewData();
                    }
                }
            }
        }

        /// <summary>
        /// 收支明细统计
        /// </summary>
        /// <param name="payments_in"></param>
        /// <param name="payments_out"></param>
        private void PaymentsCount(out decimal payments_in, out decimal payments_out)
        {
            payments_in = 0M;
            payments_out = 0M;
            try
            {
                if (dataGridView1.Rows.Count > 1)
                {
                    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                    {
                        DataGridViewRow row = dataGridView1.Rows[i];
                        decimal amount = (decimal)row.Cells["amount"].Value;
                        if (Int32.Parse(row.Cells["payments_type"].Value.ToString()) == 1)
                            payments_in += amount;
                        else if (Int32.Parse(row.Cells["payments_type"].Value.ToString()) == 2)
                            payments_out += amount;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region IDataGridViewData 成员

        void IDataGridViewData.EnterkeyEventHandler()
        {
            return;
        }

        void IDataGridViewData.GenerateGridViewColumns(DataGridView dgv)
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("id", null, true, 0, null, null, false, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("payments_name", "收支分类", true, 20, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("business", "往来单位", true, 20, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("amount", "金额", true, 10, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("payments_type", "类型", true, 10, ActKey.CENTER, ActKey.CENTER, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("payments_user", "收支人", true, 10, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("payments_time", "收支时间", true, 10, ActKey.CENTER, ActKey.CENTER, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("note", "备注", true, 20, ActKey.LEFT, ActKey.LEFT, true, false));
        }

        void IDataGridViewData.GetBindingData(int rowindex, int pageindex, int pagesize)
        {
            try
            {
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String paymentsSortid = "0";
                if(comboBoxPaymentsSort1.SelectedValue!=null)
                    paymentsSortid = comboBoxPaymentsSort1.SelectedValue.ToString();
                String startdate = String.Empty;
                String enddate = String.Empty;
                if (dateTimePicker_startdate.Checked && dateTimePicker_enddate.Checked &&
                    dateTimePicker_enddate.Value.CompareTo(dateTimePicker_startdate.Value) >= 0)
                {
                    startdate = dateTimePicker_startdate.Value.ToShortDateString();
                    enddate = dateTimePicker_enddate.Value.ToShortDateString();
                }

                DataTable dt = paymentsService.GetPaymentsTable(pageindex, pagesize, enterpriseNo, String.Empty,
                    Int32.Parse(paymentsSortid), 0, startdate, enddate);
                if (dt != null && dt.Rows.Count > 0)
                    dt.Rows.Add(dt.NewRow());
                this.dataGridView1.DataSource = dt;
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (rowindex > 0)
                        dataGridView1.Rows[0].Selected = false;
                    dataGridView1.Rows[rowindex].Selected = true;
                }
                dataGridView1.Columns[0].Visible = false;

                mainform.SetPageInfo(0, 0, 0);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        long IDataGridViewData.GetBindingDataRecord()
        {
            long record = 0;
            try
            {
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String paymentsSortid = "0";
                if (comboBoxPaymentsSort1.SelectedValue != null)
                    paymentsSortid = comboBoxPaymentsSort1.SelectedValue.ToString();
                String startdate = String.Empty;
                String enddate = String.Empty;
                if (dateTimePicker_startdate.Checked && dateTimePicker_enddate.Checked &&
                    dateTimePicker_enddate.Value.CompareTo(dateTimePicker_startdate.Value) >= 0)
                {
                    startdate = dateTimePicker_startdate.Value.ToShortDateString();
                    enddate = dateTimePicker_enddate.Value.ToShortDateString();
                }
                record = paymentsService.GetPaymentsRecord(enterpriseNo, string.Empty, Int32.Parse(paymentsSortid), 0, startdate, enddate);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return record;
        }

        #endregion

        #region 刷新数据

        /// <summary>
        /// 刷新数据
        /// </summary>
        public void RefreshDataGridViewData()
        {
            this.dataGridView1.LoadingData();
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// DataGridView单元格格式化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex==4)
            {
                String temp = e.Value.ToString();
                if (!String.IsNullOrEmpty(temp))
                {
                    if (temp.Equals("1"))
                        e.Value = "收入";
                    else if (temp.Equals("2"))
                        e.Value = "支出";
                }
            }
        }

        /// <summary>
        /// 单元格绘制事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (dataGridView1.Rows.Count > 0 && e.RowIndex == dataGridView1.Rows.Count - 1)
            {
                int lastRowIndex = e.RowIndex;
                Rectangle rect = dataGridView1.GetCellDisplayRectangle(1, lastRowIndex, false);
                int rectWidth = 0;
                foreach (DataGridViewColumn column in dataGridView1.Columns)
                {
                    if (column.Displayed)
                        rectWidth += column.Width;
                }
                rect.Width = rectWidth;

                e.Graphics.FillRectangle(new SolidBrush(dataGridView1.BackgroundColor), rect);
                using (Pen pen = new Pen(dataGridView1.GridColor, 1))
                {
                    pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
                    //上边线
                    //e.Graphics.DrawLine(pen, rect.X + rect.Width, rect.Y, rect.X + rect.Width, rect.Y + rect.Height);
                    //左边线
                    e.Graphics.DrawLine(pen, rect.X-1, rect.Y, rect.X-1, rect.Y + rect.Height);
                    //右边线
                    e.Graphics.DrawLine(pen, rect.X + rect.Width, rect.Y, rect.X + rect.Width, rect.Y + rect.Height);
                    //下边线
                    e.Graphics.DrawLine(pen, rect.X-1, rect.Y + rect.Height, rect.X + rect.Width, rect.Y + rect.Height);
                    SizeF strSize = e.Graphics.MeasureString(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(), dataGridView1.Font);

                    StringFormat sf = new StringFormat();
                    sf.Alignment = StringAlignment.Near;
                    sf.LineAlignment = StringAlignment.Center;

                    decimal payments_in = 0M, payments_out = 0M;
                    this.PaymentsCount(out payments_in, out payments_out);
                    StringBuilder sb = new StringBuilder();
                    sb.Append("总支出：").Append(payments_out.ToString("f2")).Append("    ");
                    sb.Append("总收入：").Append(payments_in.ToString("f2")).Append("    ");
                    if (payments_in > payments_out)
                        sb.Append("净收入：").Append((payments_in - payments_out).ToString("f2"));
                    else if (payments_in < payments_out)
                        sb.Append("净支出：").Append((payments_out - payments_in).ToString("f2"));
                    else
                        sb.Append("收支平衡");
                    e.Graphics.DrawString(sb.ToString(), dataGridView1.Font, Brushes.Black, rect, sf);
                    e.Handled = true;
                }
            }
        }

        /// <summary>
        /// 添加收支分类
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_addPaymentsSort_Click(object sender, EventArgs e)
        {
            PaymentsSortForm paymentsSortForm = new PaymentsSortForm(mainform, this);
            paymentsSortForm.ShowDialog();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_query_Click(object sender, EventArgs e)
        {
            this.RefreshDataGridViewData();
        }

        /// <summary>
        /// 新建收支明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_create_Click(object sender, EventArgs e)
        {
            this.ShowPaymentsAddForm(0);
        }

        #endregion


        #region 重写函数

        /// <summary>
        /// 键盘事件
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool b = base.ProcessCmdKey(ref msg, keyData);
            switch (keyData)
            {
                case Keys.F8:
                    this.RefreshDataGridViewData();
                    break;
                case Keys.F9:
                    this.ShowPaymentsAddForm(0);
                    break;
            }
            return b;
        }

        #endregion

        #region 右键菜单事件

        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_add_Click(object sender, EventArgs e)
        {
            this.ShowPaymentsAddForm(0);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_delete_Click(object sender, EventArgs e)
        {
            this.DeletePayments();
        }

        #endregion


        #region IPrinter 成员

        DataGridView IPrinter.GetAllRows()
        {
            try
            {
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String paymentsSortid = "0";
                if (comboBoxPaymentsSort1.SelectedValue != null)
                    paymentsSortid = comboBoxPaymentsSort1.SelectedValue.ToString();
                String startdate = String.Empty;
                String enddate = String.Empty;
                if (dateTimePicker_startdate.Checked && dateTimePicker_enddate.Checked &&
                    dateTimePicker_enddate.Value.CompareTo(dateTimePicker_startdate.Value) >= 0)
                {
                    startdate = dateTimePicker_startdate.Value.ToShortDateString();
                    enddate = dateTimePicker_enddate.Value.ToShortDateString();
                }

                DataTable dt = paymentsService.GetPaymentsTable(0, 0, enterpriseNo, String.Empty, Int32.Parse(paymentsSortid), 0, startdate, enddate);
                this.dataGridView1.DataSource = dt;
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return this.dataGridView1;
        }

        DataGridView IPrinter.GetSelectedRows()
        {
            return this.dataGridView1;
        }

        void IPrinter.VisibleColumn(string columnname)
        {
            try
            {
                if (this.dataGridView1.Columns[columnname].Visible)
                    this.dataGridView1.Columns[columnname].Visible = false;
                else
                    this.dataGridView1.Columns[columnname].Visible = true;
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        #endregion
    }
}
